import { phoneValidator } from '../validate'

let comLoginForm = function(options = {}) {
  var mobileEle = document.getElementById(options.mobileId)
  // var codeEle = document.getElementById(options.codeId)
  var sendEle = document.getElementById(options.sendId)

  let timer = null
  let gutter = 1000
  function reloadTimer(time) {
    let v = time / 1000
    if (v > 0) {
      if (options && options.onLoadTime) {
        options.onLoadTime(sendEle, v)
      }
      timer = setTimeout(() => {
        reloadTimer(time - gutter)
      }, gutter)
    } else {
      clearTimeout(timer)
      if (options && options.onCodeTimeout) {
        options.onCodeTimeout(sendEle)
      }
      timer = null
    }
  }

  sendEle.addEventListener('click', function() {
    // console.log('sdsds')
    if (!timer) {
      phoneValidator.validate({value: mobileEle.value}, (errors, fields) => {
        if(errors) {
          // validation failed, errors is an array of all errors
          // fields is an object keyed by field name with an array of
          // errors per field
          console.log(errors, fields)
        } else {
          // validation passed
          if (options && options.canSendCode) {
            options.canSendCode().then(() => {
              reloadTimer(options.time)
            })
          }
        }
      })
    }
  })
}


let initLoginForm = function(context) {
  var fieldF3code = context.$refs['field-f3-code']
  let initStyle = 'right: 1.2rem'
  let loadingStyle = 'right: 1.6rem'

  fieldF3code.setCloseStyle(initStyle)
  comLoginForm({
    mobileId: 'f3mobile',
    codeId: 'f3',
    sendId: 'f3sendcode',
    canSendCode() {
      return Promise.resolve(1)
    },
    onLoadTime(sendEle, v) {
      fieldF3code.setCloseStyle(loadingStyle)
      sendEle.textContent = `${v}秒后重新发送`
    },
    onCodeTimeout(sendEle) {
      fieldF3code.setCloseStyle(initStyle)
      sendEle.textContent = `获取验证码`
    },
    time: 60000
  })
}

import { MyFieldVue } from '../components/field/field'

window.initLoginApp = (el, template) => {
  new Vue({
    el,
    template,
    components: {
      'my-field': MyFieldVue
    },
    mounted() {
      initLoginForm(this)
    }
   })
}
